package com.hmall.search.listen;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hmall.common.feign.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.search.constant.EsConstant;
import com.hmall.search.constant.MqConstant;
import com.hmall.search.pojo.ItemDto;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 监听类
 *
 * @Name ITEMListener
 * @Author admin
 * @Date 2022-08-09 9:17
 */
@Component
public class HotelListener {

    @Autowired
   private ItemClient itemClient;

    @Autowired
    private RestHighLevelClient client;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(MqConstant.ITEM_INSERT_QUEUE),
                    exchange = @Exchange(value = MqConstant.ITEM_EXCHANGE, type = ExchangeTypes.DIRECT),
                    key = MqConstant.ITEM_INSERT_KEY
            )
    })
    public void listenItemInsert(String id) throws Exception {
        //1.根据id查询酒店数据
        Item item  = itemClient.getById(Long.valueOf(id));
        ItemDto itemDto = new ItemDto(item);
        //2.插入到es
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(itemDto);

        IndexRequest indexRequest = new IndexRequest(EsConstant.Itme_INDEX);
        //设置文档ID
        indexRequest.id(id);
        //设置文档数据
        indexRequest.source(json, XContentType.JSON);
        client.index(indexRequest, RequestOptions.DEFAULT);
    }

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(MqConstant.ITEM_DELETE_QUEUE),
                    exchange = @Exchange(value = MqConstant.ITEM_EXCHANGE, type = ExchangeTypes.DIRECT),
                    key = MqConstant.ITEM_DELETE_KEY
            )
    })
    public void listenItemDelete(String id) throws Exception {
        DeleteRequest deleteRequest = new DeleteRequest(EsConstant.Itme_INDEX, id);
        client.delete(deleteRequest, RequestOptions.DEFAULT);

    }

}